﻿using Application.StockWarningService;
using Domain.Entity.sys;
using Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Application.ISale_hService;
using Domain.Entity.search;
using Domain.Entity.zct;
using Microsoft.Extensions.Caching.Distributed;
using System.Drawing.Printing;
using System.Runtime.Intrinsics.Arm;
using System.Text.Json;
using Hangfire;
using WMSManage.Filter;
using Microsoft.AspNetCore.SignalR;
using WMSManage.Hubs;

namespace WMSManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]//需要鉴权
    public class StockWarningController : ControllerBase
    {
        private readonly IStockWarningService stockWarningService;
        private readonly IDistributedCache distributedCache;
        private readonly IHubContext<ChatHub> hubContext;

        public StockWarningController(IStockWarningService stockWarningService,IDistributedCache distributedCache, IHubContext<ChatHub> hubContext)
        {
            this.stockWarningService = stockWarningService;
            this.distributedCache = distributedCache;
            this.hubContext = hubContext;
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="fenYe"></param>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="warning"></param>
        /// <param name="startnum"></param>
        /// <param name="endnum"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<StockWarning>> GetStockWarning(string? name, string? type, string? warning, int? startnum, int? endnum,int CurrentPage)
        {
            //缓存键
            string key = "StockWarning" +name+type+warning+startnum+endnum+CurrentPage;
            //从缓存中获取数据
            var data = await distributedCache.GetStringAsync(key);
            if (data != null)
            {
                //从缓存中查
                return JsonSerializer.Deserialize<FenYe<StockWarning>>(data);
            }
            //从数据库查
            FenYe<StockWarning> fenYe = new FenYe<StockWarning>
            {
                CurrentPage = CurrentPage,
            };
            var result = await stockWarningService.GetStockWarning(fenYe,name,type,warning,startnum,endnum);
            //将查询到的结果存入缓存
            if (result != null)
            {
                var option = new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)//10分钟
                };
                await distributedCache.SetStringAsync(key, JsonSerializer.Serialize(result), option);
            }
            return result;
        }


        /// <summary>
        /// 库存预警刷新
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="warning"></param>
        /// <param name="startnum"></param>
        /// <param name="endnum"></param>
        /// <param name="CurrentPage"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Refresh(string? name, string? type, string? warning, int? startnum, int? endnum, int CurrentPage)
        {
            //缓存键
            string key = "StockWarning" + name + type + warning + startnum + endnum + CurrentPage;

            // 清除缓存键
            distributedCache.Remove(key);

            // 返回成功消息
            return Ok(new { success = true, message = "ok" });
        }



        /// <summary>
        /// 上下限预警
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CheckWarning()
        {
            //* * * * * 每分钟
            //0 */2 * * * 每两小时
            RecurringJob.AddOrUpdate("库存预警检查", () => ExecuteCheckWarningWithNotification(), "0 */2 * * *", new RecurringJobOptions
            {
                TimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time")
            });

            return Ok("已启动每两小时库存预警检查");
        }

        /// <summary>
        /// 执行库存预警并发送通知
        /// </summary>
        [HttpPost]
        public async Task ExecuteCheckWarningWithNotification()
        {
            // 执行预警检查
            await stockWarningService.CheckWarning();

            // 发送通知
            await hubContext.Clients.All.SendAsync("ReceiveMessage",
                "库存预警",
                "有新的库存预警信息，注意查看");
        }



        /// <summary>
        /// 到期预警
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ExpirationWarning()
        {
            //0 0 * * *每天午夜0点
            RecurringJob.AddOrUpdate("库存预警检查", () =>ExecuteExpirationWarningWithNotification(), "0 0 * * *", new RecurringJobOptions
            {
                TimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time")
            });

            return Ok("已启动每天库存到期预警检查");
        }


        /// <summary>
        /// 执行到期预警并发送通知
        /// </summary>
        [HttpPost]
        public async Task ExecuteExpirationWarningWithNotification()
        {
            // 执行预警检查
            await stockWarningService.ExpirationWarning();

            // 发送通知
            await hubContext.Clients.All.SendAsync("ReceiveMessage",
                "到期预警",
                "有新的到期预警信息，注意查看");
        }
    }
}
